<?php
require 'vendor/autoload.php';

class RssSourceManager {
	private $dbConnection;
	private $property = 'properties/rssFeeds.xml';
	
	
	function __construct($dbConnector) { 
		$this->dbConnection = $dbConnector->connectToDB();
	}
	
	public function validateAllSourcesExistOnDB(){
		
		$arrayRss = simplexml_load_file($this->property);
		$arrayNewsAll = array();
		foreach ($arrayRss as $rss) {
			$this->sourceIsLoadedInDB($rss);
			
		}
	}
	
	private function insertNewSource($rss){
		$queryHandler = $this->dbConnection->prepare('INSERT INTO sources (Name, Shortname, Type) value (:name,:shortName,:type)');
			$params = array(
				'name' => $rss->name,
			    'shortName'  =>  $rss->shortName,
				'type' => $rss->type,
			);
			$result = $queryHandler->execute($params);
			return ($result);
	}
	
	
	
	private function sourceIsLoadedInDB($rss){
		$rssShortName = $rss->shortName;
		$queryHandler = $this->dbConnection->prepare('SELECT * FROM sources WHERE ShortName = :shortname');
		$queryHandler->setFetchMode(PDO::FETCH_OBJ);
		$queryHandler->bindParam(':shortname', $rssShortName);
		$queryHandler->execute();
		$queryResult = $queryHandler->fetch();
		if ($queryResult == false){
			$result = $this->insertNewSource($rss);
		}
	}
	
	public function getSourceID($shortName){
		$queryHandler = $this->dbConnection->prepare('SELECT Id FROM sources WHERE ShortName = :shortname');
		$queryHandler->setFetchMode(PDO::FETCH_OBJ);
		$queryHandler->bindParam(':shortname', $shortName);
		$queryHandler->execute();
		$queryResult = $queryHandler->fetch();
		$sourceID = $queryResult->Id;
		return($sourceID);
	}
	
}
?>